package net.jeanhwea.ex2;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;



import net.jeanhwea.util.*;
public class FormGet {
	
	private boolean advance(ParseHtml parse, String tag, int count) throws IOException {
		int ch;
		while((ch = parse.read()) != -1) {
			if(ch == 0){
				if(parse.getTag().getName().equalsIgnoreCase(tag)){
					count--;
					if(count <= 0){
						return true;
					}
				}
			}
		}
		return true;
	}
	
	private void processItem(String item){
		System.out.println(item.trim());
	}
	
	public void process(String search, String type) throws IOException {
		String listType = "ul";
		String listTypeEnd = "/ul";
		StringBuilder buffer = new StringBuilder();
		boolean capture = false;
		
		// build the URL
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		Form form = new Form(bos, null);
		form.add("search", search);
		form.add("type", type);
		form.add("action", "Search");
		form.complete();
		
		String surl = "http://www.httprecipes.com/1/7/get.php?" + bos.toString();
		URL url = new URL(surl);
		InputStream is = url.openStream();
		ParseHtml parse = new ParseHtml(is);
		
		advance(parse, listType, 0);
		
		int ch;
		while((ch = parse.read()) != -1){
			if(ch == 0){
				HtmlTag tag = parse.getTag();
				if(tag.getName().equalsIgnoreCase("li")) {
					if(buffer.length() > 0) {
						processItem(buffer.toString());
					}
					buffer.setLength(0);
					capture = true;
				} else if (tag.getName().equalsIgnoreCase("/li")) {
					processItem(buffer.toString());
					buffer.setLength(0);
					capture = false;
				} else if(tag.getName().equalsIgnoreCase(listTypeEnd)){
					processItem(buffer.toString());
					break;
				}
			}else {
				if(capture){
					buffer.append((char) ch);
				}
			}
		}
		
	}

	public static void main(String[] args) {
		FormGet parse = new FormGet();
		try {
			parse.process("etwe", "sww");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
